<?php

declare(strict_types=1);

namespace app\backend\middleware;

use app\Request;
use think\facade\Cache;
use app\common\exception\MyException;

/**
 * 检查重复提交中间件
 */
class CheckRepeatSubmit
{

  public function handle(Request $request, \Closure $next)
  {
    // 只检查POST数据
    if ($request->method() == 'POST') {
      $post = $request->post();
      // $post['crs_time'] = time();//此限制只阻止同一秒内产生的重复提交，并不阻止每隔一秒发送一次的重复提交
      // 转md5
      $key = "checkRepeat-" . md5(json_encode($post));
      if (Cache::get($key)) {
        throw new MyException(['code' => 1001, 'msg' => '正在处理中，请勿重复提交！']);
        exit();
      }
      // 缓存时间(10秒)
      Cache::set($key, 1, 5);//5秒内不能重复
    }
    return $next($request);
  }
}
